let app = getApp();

Page({
  data: {
    fidc:"",
    wuliaoListTop:{},
    searchTimer:"",  //订单单号输入的内容
    saomaWuliao:"",  //下面扫码的物料结果
    // searchInput:"",
    searchInput:"",
    inputNumber:"",
    wuliaoList:[],
    selectedData:[],

    xiangInput:"",
    guigeInput:"",
    tijiInput:"",
    zhongInput:"",

    names: ['20*30*40', '30*40*50',  '47*34*80', '36*67*66','20*30*40', '30*40*50'],
    isHidden: true, //是否显示弹出框
    sousuoyvalue:"",   //在搜索框里输入的内容
    isSearchListShow: true,   //显示接口数据
    matchedNameList: [],   //通过filter方法对this.data.names数组进行过滤，筛选出与用户输入的关键字匹配的项，并将结果存储在matchedNameList中。
    selectedName:""    //点击后的赋值

  },
  onLoad(options) {
    var that = this
    console.log("下推接收到的 id：", options.id);
    if (options.id) {
        that.setData({
          fidc: options.id
        })
      }
      console.log("id=====================>",this.data.fidc);
    that.getPurchaseInquire()

    that.setData({
      selectedData:[]
    });
    
  },

  onShow(){
    var that = this
    // that.setData({
    //   selectedData:[]
    // });
  },


  // 选择仓库有关的
  dianji(e){
    console.log("点击了");
    const namesArray = this.data.names;
    this.setData({
      isHidden: !this.data.isHidden,
      showMask: true,
      matchedNameList: namesArray // 将型号names列表数据赋值给matchedNameList
    })
  },

  bindNameChange(e) {
    var that = this
    console.log("点击下拉内容事件触发了");
    let name = e.currentTarget.dataset.item;  // 通过e.currentTarget.dataset.item获取了用户点击的下拉列表中的项的数据，
    console.log("点击的下拉列表中的项的数据nnnnnnnnnnnnnnn",name);
  
    var selectedName = name
      // 更新 data 中的 selectedName
      that.setData({
        selectedName: selectedName,
        isHidden: !this.data.isHidden,
        showMask: false
      });
      console.log("点击的下拉列表中的项的数据赋值datannnnnnnnnnnnnnn", selectedName);
  },

  bindNameInput2(e) {
    var that = this
    console.log("获取内容事件触发了",e);
    const keyword = e.detail.value.toLowerCase();   //通过e.detail.value获取用户在输入框中输入的值，并将其转换为小写字母格式（toLowerCase()）。
    console.log("keyword我在搜索框输入的仓库id",keyword);

    const reg = new RegExp(keyword);   // 创建一个正则表达式reg，用于匹配用户输入的关键字。 筛选匹配项时，使用的是keyword变量
    console.log("reg",reg);
    const matchedNameList = this.data.names.filter(item => reg.test(item[0].toLowerCase()));  //通过filter方法对this.data.names数组进行过滤，筛选出与用户输入的关键字匹配的项，并将结果存储在matchedNameList中。

    this.setData({ matchedNameList });     //使用setData方法将matchedNameList更新到页面数据中，以便在界面上展示匹配的结果，并打印出匹配的结果。
    console.log("matchedNameList",matchedNameList);

    var that = this
    that.setData({
      sousuoyvalue: keyword
    })
  },


  // 订单明细
  getPurchaseInquire() {
    var that = this;
    var fidpd = that.data.fidc
    console.log("订单明细数据fid",fidpd);
  
    var data = JSON.stringify(
      {
        "xx": {
          "formId": "ZYKJ_ZXD",
          "fields": [
            "FID","FBillNo","F_ZYKJ_Date_1xj","F_ZYKJ_Text_k79"
          ],
          "FilterString": "FID='"+ fidpd +"'",
          "orderby": "",
          "topRowCount": 0,
          "limit": 0,
          "StartRow": 0,
          "fields_name": [
            "FID","箱码编号","装箱日期","订单号"
          ],
          "acctID": "66249c7f42e1e4"
        },
        "login": {
          "username": "test",
          "password": "zz333333"
        }
      }
    )
  
    // return
    dd.httpRequest({
      url: 'http://cloud.reece-sewing.com:9351/king_query',
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      data: data,
      dataType: 'json',
      success: function (res) {
        if (res.data.code == 200) {
          console.log("装箱单200",res.data);
          var orderMaterialCodeListTop = res.data.data;
  
          that.setData({
            wuliaoListTop: orderMaterialCodeListTop,
          });
  
          console.log("jieguoooooooooooooo",that.data.wuliaoListTop);
  
          // 在订单明细获取成功后再获取分解明细数据
          // that.getPurchaseFenjie();
  
        } else {
          dd.showToast({
            type: 'fail',
            content: res.data.data,
            duration: 2000,
          });
        }
      },
      fail: function (res) {
        console.log("订单明细调用失败",res);
      },
      complete: function (res) {
      }
    });
  },

  onSearchInput(e) {
    var that = this;
    var searchTerm = e.detail.value.trim(); // 获取输入框的搜索内容并去除首尾空格
    console.log("输入框用来查的内容", searchTerm);
    // 将定时器存储在数据中
    that.setData({
        searchTimer: searchTerm
    });
    console.log("订单单号输入的内容",that.data.searchTimer);
  },

  //点击确认按钮根据订单号输入搜索判定下面扫码的物料编码是否在这个订单号上
  querenIf() {
  var that = this;

  var saomaWuliao = that.data.saomaWuliao.slice(0, 11); // 截取前11位扫码结果

  var searchTimer = that.data.searchTimer
  console.log("过滤输入的订单号",searchTimer);

  // var data = JSON.stringify(
  //   {
  //     "xx": {
  //       "formId": "ZYKJ_PHD",
  //       "fields": [
  //         "FID,FBillNo,F_ZYKJ_Text_k79,F_ZYKJ_Base_apv11,F_ZYKJ_Base_3iy.fnumber"
  //       ],
  //       "FilterString": "F_ZYKJ_Text_k79='"+ searchTimer +"'",
  //       "orderby": "",
  //       "topRowCount": 0,
  //       "limit": 0,
  //       "StartRow": 0,
  //       "fields_name": [
  //         "FID","单据编号","订单号","客户编码","物料编码"
  //       ],
  //       "acctID": "66249c7f42e1e4"
  //     },
  //     "login": {
  //       "username": "test",
  //       "password": "zz333333"
  //     }
  //   }
  // )

  var data = JSON.stringify(
    {
      "xx": {
        "formId": "ZYKJ_SCRWD",
        "fields": [
          "FID,FBillNo,F_ZYKJ_Text,F_ZYKJ_Base1.fnumber"
        ],
        "FilterString": "F_ZYKJ_Text='"+ searchTimer +"'",
        "orderby": "",
        "topRowCount": 0,
        "limit": 0,
        "StartRow": 0,
        "fields_name": [
          "FID","单据编号","订单号","物料编码"
        ],
        "acctID": "66249c7f42e1e4"
      },
      "login": {
        "username": "test",
        "password": "zz333333"
      }
    }
  )


  console.log("点击确认按钮的date",data);

  // return
  dd.httpRequest({
    url: 'http://cloud.reece-sewing.com:9351/king_query',
    method: 'POST',
    headers: {
      "Content-Type": "application/json"
    },
    data: data,
    dataType: 'json',
    success: function (res) {
      if (res.data.code == 200) {
        console.log("配货单200",res.data);

        var orderMaterialCodeList = res.data.data;
        that.setData({
            wuliaoList: orderMaterialCodeList,
        });

        // console.log("扫码物料结果", saomaWuliao);

        console.log("jieguoooooooooooooo",that.data.wuliaoList);
     
      } else {
        dd.showToast({
          type: 'fail',
          content: res.data.data,
          duration: 2000,
        });
      }
    },
    fail: function (res) {
      console.log("订单明细调用失败",res);
    },
    complete: function (res) {
    }
  });
  },


  // 扫码
  onSearchShop() {
    var that = this;
    dd.scan({
      type: 'qr',
      success: (res) => {
          console.log("扫码结果", res.code);
          that.setData({
            saomaWuliao: res.code
        });
        console.log("扫码物料结果",that.data.saomaWuliao);

        // 扫码成功后，对比扫码结果和后台数据
        that.compareWithBackendData();
      },
      fail: (err) => {
          // 扫码失败后的回调函数，可以根据实际需求进行处理
      }
  });
  },


  // 监听扫描的编码
  onSearchInputs(e) {
  var that = this;
  var searchInput = e.detail.value.trim(); // 获取输入框的搜索内容并去除首尾空格
  console.log("扫码后的内容", searchInput);
  // 将定时器存储在数据中
  that.setData({
    searchInput: searchInput
  });
  console.log("扫码后的内容",that.data.searchInput);
},

// 监听扫描的数字
oninputNumber(e) {
  var that = this;
  var inputNumber = e.detail.value.trim(); // 获取输入框的搜索内容并去除首尾空格
  console.log("扫码后的内容n", inputNumber);
  // 将定时器存储在数据中
  that.setData({
    inputNumber: inputNumber
  });
  console.log("扫码后的内容n",that.data.inputNumber);
},


// 对比扫码结果和后台数据
compareWithBackendData() {
  var that = this;
  var saomaWuliaose = that.data.saomaWuliao.slice(0, 11); // 截取前11位扫码结果
  var orderMaterialCodeList = that.data.wuliaoList;

  // dd.confirm({
  //   title: '温馨提示',
  //   content: saomaWuliaose,
  //   confirmButtonText: '确定',
  //   cancelButtonText: 'no',
  // });

  console.log("扫码物料结果", saomaWuliaose);
  console.log("后台订单物料列表", orderMaterialCodeList);

  var isMatched = orderMaterialCodeList.some(item => item.物料编码 === saomaWuliaose);
  if (isMatched) {
    console.log("扫码物料存在于订单物料编码列表中");
    that.setData({
      searchInput: saomaWuliaose, // 将扫码截取前11位扫码结果赋值给searchInput
      inputNumber: that.data.saomaWuliao.slice(11) // 将扫码结果除去前11位的部分赋值给inputNumber
    });
    that.onSearchInputs(); // 手动触发输入框的输入事件
    that.oninputNumber(); // 手动触发 inputNumber 输入框的输入事件
  } else {
      console.log("扫码物料不存在于订单物料编码列表中");
      dd.showToast({
        type: 'fail',
        content: '扫码物料不存在于订单物料编码列表中',
        duration: 2000,
      });
  }
},

querenSaomac(){
  var that = this;
  var selectedData = that.data.selectedData;

  var searchInput = that.data.searchInput
  console.log("扫描的编码",searchInput);

  var inputNumber = that.data.inputNumber
  console.log("扫描的数量",inputNumber);
  var inputNumber = parseInt(inputNumber);

  // 构造要添加的数据对象
  var newData = {
  物料编码: searchInput,
  基本单位数量: inputNumber
  };

  // 将新数据对象添加到selectedData列表中
  selectedData.push(newData);

  // 更新data中的selectedData
  that.setData({
  selectedData: selectedData,
  searchInput: "", // 将扫码结果赋值给searchInput之后清空
  inputNumber: "" // 将扫码结果除去前11位的部分赋值给inputNumber之后清空
  });
  console.log("扫码得到的列表",that.data.selectedData);

    //   dd.confirm({
    //   title: '温馨提示',
    //   content: that.data.selectedData,
    //   confirmButtonText: '确定',
    //   cancelButtonText: 'no',
    // });
},

onXiangInput(e){
  var that = this
  var xiangInput = e.detail.value
  that.setData({
    xiangInput: xiangInput,
  });
  console.log("这是输入的箱号",that.data.xiangInput);
},

onGuigeInput(e){
  var that = this
  var guigeInput = e.detail.value
  that.setData({
    guigeInput: guigeInput,
  });
  console.log("这是输入的规格",that.data.guigeInput);
},

onTijiInput(e){
  var that = this
  var tijiInput = e.detail.value
  that.setData({
    tijiInput: tijiInput,
  });
  console.log("这是输入的体积",that.data.tijiInput);
},

onZhongInput(e){
  var that = this
  var zhongInput = e.detail.value
  that.setData({
    zhongInput: zhongInput,
  });
  console.log("这是输入的重量",that.data.zhongInput);
},

  // 确定修改 添加单据体
  qurrenBtny(e) {
    var that = this
    var selectedData = that.data.selectedData; 

     // 3.通过循环将拿到的数据转换为接口所需要的数据结构
     var F_ZYKJ_CGRK_Entry = []
     for(var i =0; i<selectedData.length; i++){
       F_ZYKJ_CGRK_Entry.push({
         "FEntryID": 0,                                                     //行id
         "F_ZYKJ_Base_3iy":  {"FNUMBER": selectedData[i].物料编码},         //单据编码
         "F_ZYKJ_BaseQty_pzg": selectedData[i].基本单位数量,                //基本单位数量
        //  "F_ZYKJ_Base_re51":{"FNUMBER": ""},   
         "F_ZYKJ_Assistant_tzk":{"FNUMBER": ""},                
         "F_ZYKJ_Base_re5": { "FNUMBER": ""},                               //仓位
         "F_ZYKJ_Base_qtr": {"FNUMBER": app.globaldata.user['员工工号']},   //拣货员
       })
     }
     console.log("点击提交按钮修改后的item为true的接口所需要的数据结构",F_ZYKJ_CGRK_Entry);

    var fidpd = that.data.fidc
    var searchTimer = that.data.searchTimer  //输入的订单号确定修改
    var xiangInput = that.data.xiangInput  //箱号
    var guigeInput = that.data.selectedName  //下拉选中的规格
    var tijiInput = that.data.tijiInput   //体积
    var zhongInput = that.data.zhongInput //重量

    // "model": {  "FID": fidpd,"F_ZYKJ_Text_k79": searchTimer,"F_ZYKJ_ZXD_Entry":F_ZYKJ_CGRK_Entry},
    
    var data = JSON.stringify(
      {
        "save": {
          "formid": "ZYKJ_ZXD",
          "model": {  "FID": fidpd,"F_ZYKJ_Text_k79": searchTimer,"F_ZYKJ_Text_ca9": xiangInput,"F_ZYKJ_Qty_dvn": tijiInput,"F_ZYKJ_Qty_w5c": zhongInput,"F_ZYKJ_Combo_yrr": guigeInput,"F_ZYKJ_ZXD_Entry":F_ZYKJ_CGRK_Entry},
          "IsAutoSubmitAndAudit": true,
          "IsDeleteEntry": false
        },
        "login": {
          "acctID": "66249c7f42e1e4",
          "url": "192.168.17.253",
          "username": "test",
          "password": "zz333333"
        }
      }
    )

    // dd.confirm({
    //   title: '温馨提示',
    //   content: data,
    //   confirmButtonText: '确定',
    //   cancelButtonText: 'no',
    // });

    my.showLoading({
      content: '',
    })
    console.log("点击提交创建的data",data);
  
    dd.httpRequest({
      url: 'http://cloud.reece-sewing.com:9351/king_save',
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      data: data,
      dataType: 'json',
      success: function (res) {
        if(res.data.code == 200){
        console.log("确定修改 添加单据体200======》",res);
       that.setData({
        selectedData:[]
        });

        dd.confirm({
          title: '温馨提示',
          content: '提交成功',
          confirmButtonText: '确认',
          cancelButtonText: '',
          success: (result) => {
            console.log(result);
            let pages = getCurrentPages();
            if (result.confirm) {
              if (pages.length >= 2) {
                dd.navigateBack({
                  delta: 1 // 返回的层级，这里表示返回两层
                });
                my.hideLoading(); // 隐藏 loading 提示框
              }
            }else {

              let pages = getCurrentPages();
              if (pages.length >= 2) { 
                dd.navigateBack({
                  delta: 1 // 返回的层级，这里表示返回两层
                });
                my.hideLoading(); // 隐藏 loading 提示框
              }
            }
      }
    });
        }else{
          my.hideLoading();
          // const errorMessage = res.data.data[0].Message;   // 获取第一个错误对象的错误信息
          // dd.alert({ content: errorMessage });
          console.log("采购入库单修改提交按钮的code!=200响应",res);
        }
      },
      fail: function (res) {
        console.log("提交按钮的fail响应",res);
        my.hideLoading();
      },
      complete: function (res) {
        my.hideLoading();
      }
    });
  },

    // 暂存修改 添加单据体
    qurrenBtnyZc(e) {
      var that = this
      var selectedData = that.data.selectedData; 
   
       var F_ZYKJ_CGRK_Entry = []
       for(var i =0; i<selectedData.length; i++){
         F_ZYKJ_CGRK_Entry.push({
           "FEntryID": 0,                                                     //行id
           "F_ZYKJ_Base_3iy":  {"FNUMBER": selectedData[i].物料编码},         //单据编码
           "F_ZYKJ_BaseQty_pzg": selectedData[i].基本单位数量,                //基本单位数量
          //  "F_ZYKJ_Base_re51":{"FNUMBER": ""},   
           "F_ZYKJ_Assistant_tzk":{"FNUMBER": ""},         
           "F_ZYKJ_Base_re5": { "FNUMBER": ""},                               //仓位
           "F_ZYKJ_Base_qtr": {"FNUMBER": app.globaldata.user['员工工号']},   //拣货员
         })
   
       }
       console.log("点击提交按钮修改后的item为true的接口所需要的数据结构",F_ZYKJ_CGRK_Entry);
  
      var fidpd = that.data.fidc
      var searchTimer = that.data.searchTimer  //输入的订单号确定修改
      var xiangInput = that.data.xiangInput   //箱号
      var guigeInput = that.data.selectedName  //下拉选中的规格
      console.log("guigeInput",guigeInput);
      var tijiInput = that.data.tijiInput   //体积
      var zhongInput = that.data.zhongInput //重量
  
      // "model": {  "FID": fidpd,"F_ZYKJ_Text_k79": searchTimer,"F_ZYKJ_ZXD_Entry":F_ZYKJ_CGRK_Entry},

      var data = JSON.stringify(
        {
          "save": {
            "formid": "ZYKJ_ZXD",
            "model": {  "FID": fidpd,"F_ZYKJ_Text_k79": searchTimer,"F_ZYKJ_Text_ca9": xiangInput,"F_ZYKJ_Qty_dvn": tijiInput,"F_ZYKJ_Qty_w5c": zhongInput,"F_ZYKJ_Combo_yrr": guigeInput,"F_ZYKJ_ZXD_Entry":F_ZYKJ_CGRK_Entry},
            "IsAutoSubmitAndAudit": false,
            "IsDeleteEntry": false
          },
          "login": {
            "acctID": "66249c7f42e1e4",
            "url": "192.168.17.253",
            "username": "test",
            "password": "zz333333"
          }
        }
      )

      my.showLoading({
        content: '',
      })
      console.log("点击提交创建的data",data);
    
      dd.httpRequest({
        url: 'http://cloud.reece-sewing.com:9351/king_save',
        method: 'POST',
        headers: {
          "Content-Type": "application/json"
        },
        data: data,
        dataType: 'json',
        success: function (res) {
          if(res.data.code == 200){
          console.log("确定修改 添加单据体200======》",res);
       
         that.setData({
          selectedData:[]
          });
  
          dd.confirm({
            title: '温馨提示',
            content: '提交成功',
            confirmButtonText: '确认',
            cancelButtonText: '',
            success: (result) => {
              console.log(result);
              let pages = getCurrentPages();
              if (result.confirm) {
                if (pages.length >= 2) {
                  dd.navigateBack({
                    delta: 1 // 返回的层级，这里表示返回两层
                  });
                  my.hideLoading(); // 隐藏 loading 提示框
                }
              }else {
  
                let pages = getCurrentPages();
                if (pages.length >= 2) {
                  dd.navigateBack({
                    delta: 1 // 返回的层级，这里表示返回两层
                  });
                  my.hideLoading(); // 隐藏 loading 提示框
                }
              }
        }
      });
  
          }else{
            my.hideLoading(); // 隐藏 loading 提示框
            // const errorMessage = res.data.data[0].Message;   // 获取第一个错误对象的错误信息
            // dd.alert({ content: errorMessage });
            console.log("采购入库单修改提交按钮的code!=200响应",res);
          }
       
        },
        fail: function (res) {
          console.log("提交按钮的fail响应",res);
          my.hideLoading();
        },
        complete: function (res) {
          my.hideLoading();
        }
      });
    },

});
